<?php
/**
 * Created by PhpStorm.
 * User: ASUS
 * Date: 2021/9/7
 * Time: 14:39
 */

namespace app\api\controller;


class Kayapay extends Base
{
    /**
     * @author ASUS
     * @date 2021-08-20 14:10
     * 查询Kaya代付余额
     */
    public function getKayaBalance()
    {
        $config = db("product")->where(["product_name"=>"dkpay"])->find();
        $url = $config['url']."/account";
        $merchantCode =  $config["mch_id"];
        $params = array(
            'merchantCode' => $merchantCode,
            'dateTime' => date("YmdHis")
        );
        ksort($params);
        $params_str = '';
        foreach ($params as $key => $val) {
            $params_str = $params_str . $val;
        }
        $sign = $this->private_key_encrypt($params_str, $config["pri_key"]);
        $params['sign'] = $sign;
        $res = http_post_flin($url,$params);
        $data = ["balance"=>$res["balance"],"freeze"=>$res["freeze"]];
        api_return(200,"成功",$data);
    }
    /**
     * @param $data
     * @param $pivate_key
     * @return string
     * @author ASUS
     * @date 2020-11-26 13:48
     * kayapay私钥格式化
     */
    private function private_key_encrypt($data, $private_key)
    {
        $private_key = '-----BEGIN PRIVATE KEY-----'."\n".$private_key."\n".'-----END PRIVATE KEY-----';
        $pi_key = openssl_pkey_get_private($private_key);
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_private_encrypt($chunk, $encryptData, $pi_key);
            $crypto .= $encryptData;
        }
        return base64_encode($crypto);
    }
    /**
     * @author ASUS
     * @date 2021-09-07 14:40
     * kayapay代付
     */
    public function df()
    {
//        $json = [
//            "status"=>203,
//            "msg"=>"代付功能暂时关闭",
//            "data"=>[]
//        ];
//        return json($json);
        $post = file_get_contents('php://input');//接受的post数据
        $param = json_decode($post, true);//转成数组
        if(empty($param)){
            $json = [
                "status"=>-1,
                "msg"=>"参数缺失",
                "data"=>[]
            ];
            return json($json);
        }
        $product_amount = db("admin_product_amount")->where(["admin_id"=>$param["mch_id"],"product_id"=>2])->find();
        if($param["df_amount"]<10000000){
            $df_free = 5000+$param["df_amount"]*0.005;
        }else{
            $df_free = 5000;
        }
        $total_amount = $param["df_amount"]+$df_free;
        if($product_amount["amount"]<$total_amount){
            $json = [
                "status"=>-2,
                "msg"=>"账户余额不足",
                "data"=>[]
            ];
            return json($json);
        }
        $config = db("product")->where(["product_name"=>"dkpay"])->find();
        $url = $config['url']."/cash";//基础请求地址
        $mchId = $config["mch_id"];//商户号
        $notifyUrl = $config["df_notify_url"];//回调地址
        $postData = array(
            'merchantCode' => $mchId,
            'orderNum' => $param["df_orderno"],
            'money' => $param["df_amount"],
            'feeType' => 1,
            'dateTime' => date("YmdHis",time()),
            'name' => $param["user_name"],
            'number' => $param["card_no"],
            'bankCode' => $param["bankCode"],
            'description' => "Test Withdraw",
            'notifyUrl' => $notifyUrl//::todo
        );
        ksort($postData);
        $params_str = '';
        foreach ($postData as $key => $val) {
            $params_str = $params_str . $val;
        }
        $sign = $this->private_key_encrypt($params_str, $config["pri_key"]);
        $postData['sign'] = $sign;
        $res = http_post_flin($url,$postData);
        if($res['platRespCode']=="SUCCESS"){//成功
            $df = [
                "admin_id"=>$param["mch_id"],
                "orderno"=>$param["orderno"],
                "df_orderno"=>$param["df_orderno"],
                "username"=>$param["user_name"],
                "bank_name"=>$param["bankCode"],
                "card_no"=>$param["card_no"],
                "df_amount"=> $param["df_amount"],
                "df_free"=>$df_free,
                "k_amount"=>$param["df_amount"]+$df_free,
                "msg"=>"待到账",
                "add_time"=>time(),
                "notify_url"=>$param["notify_url"],
                "paymethod"=>"dkpay"
            ];
            db("df")->insert($df);//记下代付记录
            $json = [
                "status"=>200,
                "msg"=>"success",
                "data"=>$res
            ];
            return json($json);
        }else{
            $json = [
                "status"=>203,
                "msg"=>"fail",
                "data"=>$res
            ];
            return json($json);
        }
    }

    /**
     * @author ASUS
     * @date 2021-09-07 15:03
     * 代付回调
     */
    public function dfNotify()
    {
        $post = file_get_contents('php://input');//接受的post数据
        log_write("dk_df",$post);//写入日志
        $param = convert_url_query($post);
        $df_orderno = $param['orderNum'];//支付订单号
        $df = db("df")->where(["df_orderno"=>$df_orderno])->find();
        if($df["status"]==1){
            echo "SUCCESS";
            die();
        }
        if ($param['status'] === '2') {//支付成功
            //1.改状态
            $df_data = [
                'status'=>1,
                'msg'=>"success",
                'notify_time'=>time()
            ];
            db("df")->where(["df_orderno"=>$df_orderno])->update($df_data);
            //2.记下扣款记录
            $free = $df["df_amount"]+$df["df_free"];
            $recode = [
                "admin_id"=>$df["admin_id"],
                "type"=>1,
                "amount"=>-$free,
                "remark"=>"代付支出",
                "product_id"=>2,
                "add_time"=>time()
            ];
            db("admin_amount_detail")->insert($recode);
            //3.扣去用户可用金额
            $free = $df["df_amount"]+$df["df_free"];
            db("admin_product_amount")->where(["admin_id"=>$df["admin_id"]])->setDec("amount",$free);
        }else{//支付失败
            $df_data = [
                'status'=>2,
                'msg'=>$param["statusMsg"],
                'notify_time'=>time()
            ];
            db("df")->where(["df_orderno"=>$df_orderno])->update($df_data);
        }
        http_post($df["notify_url"], json_encode($param));
        echo "SUCCESS";
    }
    /**
     * @author ASUS
     * @date 2020-09-15 10:25
     * kaya支付
     */
    public function zf()
    {
        $post = file_get_contents('php://input');//接受的post数据
        $param = json_decode($post, true);//转成数组
        if(empty($param)){
            $json = [
                "status"=>-1,
                "msg"=>"参数缺失",
                "data"=>[]
            ];
            return json($json);
        }
        $config = db("product")->where(["product_name"=>"dkpay"])->find();
        $url = $config['url']."/pay";//基础请求地址
        $mchId = $config["mch_id"];//商户号
        $notifyUrl = $config["zf_notify_url"];//回调地址
        $postData = array(
            'merchantCode' => $mchId,
            'payMoney' => $param["zf_amount"],
            'method' =>  $param["method"],
            'orderNum' =>  $param["zf_orderno"],
            'productDetail' => "Test Pay",
            'name' => $param["username"],
            'email' => $param["email"],
            'phone' => $param["telephone"],
            'dateTime' => date("YmdHis",time()),
            'expiryPeriod' => '1000',
            'notifyUrl' => $notifyUrl,//::todo
        );
        ksort($postData);
        $params_str = '';
        foreach ($postData as $key => $val) {
            $params_str = $params_str . $val;
        }
        $sign = $this->private_key_encrypt($params_str, $config["pri_key"]);
        $postData['sign'] = $sign;
        $res = http_post_flin($url,$postData);
//        $zf_free = db("admin_product_amount")->where(["admin_id"=>$param["mch_id"]])->value("z_free");
        if($param['method']=="FT"){
            $zf_free = 6000+$param["zf_amount"]*0.01;
        }else{
            $zf_free = 4500+$param["zf_amount"]*0.01;
        }
        if ($res['platRespCode'] == "SUCCESS") {//成功
            $zf = [
                "admin_id"=>$param["mch_id"],
                "orderno"=>$param["orderno"],
                "zf_orderno"=>$param["zf_orderno"],
                "zf_amount"=> $param["zf_amount"],
                "zf_free"=>$zf_free,
                "r_amount"=>$param["zf_amount"]-$zf_free,
                "zf_code"=>$res['vaNumber'],
                "username"=>$param["username"],
                "telephone"=>$param["telephone"],
                "notify_url"=>$param["notify_url"],
                "msg"=>"待支付",
                "add_time"=>time(),
                "paymethod"=>"dkpay({$param['method']})"
            ];
            db("zf")->insert($zf);//记下代付记录
        }
        return json($res);
    }
    /**
     * @author ASUS
     * @date 2020-11-27 13:43
     * kaya还款回调
     */
    public function zfNotify()
    {
        $post = file_get_contents('php://input');//接受的post数据
        log_write("dk_zf",$post,"pcapi");//写入日志
        $param = convert_url_query($post);
        $zf_orderno = $param['orderNum'];//支付订单号
        $zf = db("zf")->where(["zf_orderno"=>$zf_orderno])->find();
        if($zf["status"]==1){
            echo "SUCCESS";
            die();
        }
        if (($param['msg'] == "SUCCESS")) {//还款成功
            //1.更新zf表
            $zf_data = [
                "msg" => "支付成功",
                "status" => 1,
                "notify_time" => time(),
            ];
            db('zf')->where(["zf_orderno"=>$zf_orderno])->update($zf_data);
            //2.记下支付记录
            $free = $zf["zf_amount"]-$zf["zf_free"];
            $recode = [
                "admin_id"=>$zf["admin_id"],
                "type"=>2,
                "amount"=>"+$free",
                "remark"=>"支付收入",
                "product_id"=>2,
                "add_time"=>time()
            ];
            db("admin_amount_detail")->insert($recode);
            //3.增加用户可用金额
            $free = $zf["zf_amount"]-$zf["zf_free"];
            db("admin_product_amount")->where(["admin_id"=>$zf["admin_id"]])->setInc("amount",$free);
        } elseif (($param['status'] == "4")) {//还款失败
            $zf_data = [
                "msg" => "支付失败",
                "notify_time" => time(),
                "status" => 2,
            ];
            db('zf')->where(["zf_orderno" => $zf_orderno])->update($zf_data);
        }
        http_post($zf["notify_url"], json_encode($param));
        echo 'SUCCESS';
    }
    /**
     * @author ASUS
     * @date 2021-09-28 11:43
     * 提现
     */
    public function withdraw()
    {
//        $json = [
//            "status"=>203,
//            "msg"=>"提现功能暂时关闭",
//            "data"=>[]
//        ];
//        return json($json);
        $admin_id = input("admin_id");//商户id
        $amount = input("amount");//提现金额
        $user_name = input("user_name");//用户名
        $card_no = input("card_no");//银行卡号
        $bank_code = input("bank_code");//银行code
        $is_have = db("df")->where(["admin_id" => $admin_id,"status"=>0])->find();
        if($is_have&&strlen($is_have["orderno"]==16)){
            api_return(203,'存在待到账的提现,请先确认上一笔',[]);
        }
        $product_amount = db("admin_product_amount")->where(["admin_id" => $admin_id, "product_id" => 2])->find();
        if($amount<10000000){
            $df_free = 5000+$amount*0.005;
        }else{
            $df_free = 5000;
        }
        $total_amount = $df_free + $amount;
        if ($product_amount["amount"] < $total_amount) {
            api_return(203,'账户余额不足',[]);
        }
        $config = db("product")->where(["product_name" => "dkpay"])->find();
        $url = $config['url'] . "/cash";//基础请求地址
        $mchId = $config["mch_id"];//商户号
        $postData = array(
            'merchantCode' => $mchId,
            'orderNum' => date("YmdHis") . $admin_id,
            'money' => $amount,
            'feeType' => 1,
            'dateTime' => date("YmdHis", time()),
            'name' => $user_name,
            'number' => $card_no,
            'bankCode' => $bank_code,
            'description' => "Test Withdraw",
            'notifyUrl' => "https://adminpay.cmd2019.cn/api/Kayapay/withdrawNotify"//::todo
        );
        ksort($postData);
        $params_str = '';
        foreach ($postData as $key => $val) {
            $params_str = $params_str . $val;
        }
        $sign = $this->private_key_encrypt($params_str, $config["pri_key"]);
        $postData['sign'] = $sign;
        $res = http_post_flin($url, $postData);
        if ($res['platRespCode'] == "SUCCESS") {//成功
            $df = [
                "admin_id" => $admin_id,
                "orderno" => $postData["orderNum"],
                "df_orderno" => $postData["orderNum"],
                "username"=>$user_name,
                "bank_name"=>$bank_code,
                "card_no"=>$card_no,
                "df_amount" => $amount,
                "df_free" => $df_free,
                "k_amount" => $amount + $df_free,
                "msg" => "待到账",
                "add_time" => time(),
                "notify_url"=>"https://adminpay.cmd2019.cn/api/Kayapay/withdrawNotify",
                "paymethod" => "dkpay"
            ];
            db("df")->insert($df);//记下代付记录
            api_return(200,'success',[]);
        } else {
            api_return(203,"fail",[]);
        }
    }
    /**
     * @author ASUS
     * @date 2021-09-07 15:03
     * 提现回调
     */
    public function withdrawNotify()
    {
        $post = file_get_contents('php://input');//接受的post数据
        log_write("dk_wd",$post);//写入日志
        $param = convert_url_query($post);
        $df_orderno = $param['orderNum'];//支付订单号
        $df = db("df")->where(["df_orderno"=>$df_orderno])->find();
        if($df["status"]==1){
            echo "SUCCESS";
            die();
        }
        if ($param['status'] === '2') {//支付成功
            //1.改状态
            $df_data = [
                'status'=>1,
                'msg'=>"success",
                'notify_time'=>time()
            ];
            db("df")->where(["df_orderno"=>$df_orderno])->update($df_data);
            //2.记下扣款记录
            $free = $df["df_amount"]+$df["df_free"];
            $recode = [
                "admin_id"=>$df["admin_id"],
                "type"=>3,
                "amount"=>-$free,
                "remark"=>"提现支出",
                "product_id"=>2,
                "add_time"=>time()
            ];
            db("admin_amount_detail")->insert($recode);
            //3.扣去用户可用金额
            $free = $df["df_amount"]+$df["df_free"];
            db("admin_product_amount")->where(["admin_id"=>$df["admin_id"]])->setDec("amount",$free);
        }else{//支付失败
            $df_data = [
                'status'=>2,
                'msg'=>$param["statusMsg"],
                'notify_time'=>time()
            ];
            db("df")->where(["df_orderno"=>$df_orderno])->update($df_data);
        }
        echo "SUCCESS";
    }
    /**
     * @author ASUS
     * @date 2020-09-15 10:25
     * 手动生成kaya支付
     */
    public function zfTest()
    {
        $config = db("product")->where(["product_name"=>"dkpay"])->find();
        $notifyUrl = $config["zf_notify_url"];//回调地址
        $param = [
            "mch_id"=>32,
            "zf_amount"=>2000000,
            "method"=>"BT",
            "orderno"=>"20211110160600",
            "zf_orderno"=>"20211110160600_jccvpjy",
            "username"=>"NOVITA SURYANINGSIH",
            "email"=>"marigoldtest7@gmail.com",
            "telephone"=>"8128161356",
            "notify_url"=>$notifyUrl,
        ];

        $url = $config['url']."/pay";//基础请求地址
        $mchId = $config["mch_id"];//商户号
        $postData = array(
            'merchantCode' => $mchId,
            'payMoney' => $param["zf_amount"],
            'method' =>  $param["method"],
            'orderNum' =>  $param["zf_orderno"],
            'productDetail' => "Test Pay",
            'name' => $param["username"],
            'email' => $param["email"],
            'phone' => $param["telephone"],
            'dateTime' => date("YmdHis",time()),
            'expiryPeriod' => '1000',
            'notifyUrl' => $notifyUrl,//::todo
        );
        ksort($postData);
        $params_str = '';
        foreach ($postData as $key => $val) {
            $params_str = $params_str . $val;
        }
        $sign = $this->private_key_encrypt($params_str, $config["pri_key"]);
        $postData['sign'] = $sign;
        $res = http_post_flin($url,$postData);
//        $zf_free = db("admin_product_amount")->where(["admin_id"=>$param["mch_id"]])->value("z_free");
        if($param['method']=="FT"){
            $zf_free = 6000+$param["zf_amount"]*0.01;
        }else{
            $zf_free = 4500+$param["zf_amount"]*0.01;
        }
        if ($res['platRespCode'] == "SUCCESS") {//成功
            $zf = [
                "admin_id"=>$param["mch_id"],
                "orderno"=>$param["orderno"],
                "zf_orderno"=>$param["zf_orderno"],
                "zf_amount"=> $param["zf_amount"],
                "zf_free"=>$zf_free,
                "r_amount"=>$param["zf_amount"]-$zf_free,
                "zf_code"=>$res['vaNumber'],
                "username"=>$param["username"],
                "telephone"=>$param["telephone"],
                "notify_url"=>$param["notify_url"],
                "msg"=>"待支付",
                "add_time"=>time(),
                "paymethod"=>"dkpay({$param['method']})"
            ];
            db("zf")->insert($zf);//记下代付记录
        }
        return json($res);
    }
    public function doNopay()
    {
        $zfArr = [];//支付订单号
        $o = [];
        foreach ($zfArr as $k=>$v){
            $pa = db("zf")->where(["zf_orderno"=>$v])->find();
            if($pa){
                $o[] = $v;
                db("zf")->where(["zf_orderno"=>$v])->update(["status"=>0,"notify_time"=>0,"msg"=>"未支付"]);
                db("admin_product_amount")->where(["admin_id"=>$pa["admin_id"]])->setDec("amount",$pa["r_amount"]);
            }
        }
        dump($o);
        die();
    }
}